/*
 * @(#)PidAllocateServlet.java
 * Date 2013-09-20
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.registry.web;

import java.io.IOException;

import javax.inject.Inject;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import us.hornerscorners.lamppost.exception.ServiceActionException;

import us.hornerscorners.lamppost.ihecommon.config.IHEConfig;


import us.hornerscorners.lamppost.model.common.InstanceIdentifier;

import us.hornerscorners.lamppost.registry.service.IPatientIdentityService;

import us.hornerscorners.lamppost.utils.UUIDUtils;


/**
 * Class description
 *
 *
 * @version        v1.0, 2013-09-20
 * @author         Jim Horner
 */
@WebServlet(urlPatterns = { "/pidallocate" })
public class PidAllocateServlet extends HttpServlet {

    /** Field description */
    @Inject
    private IHEConfig iheConfig;

    /** Field description */
    @Inject
    private IPatientIdentityService patientIdentityService;

    /**
     * Method description
     *
     *
     * @param req
     * @param resp
     *
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String uuid = StringUtils.replace(UUIDUtils.generate(), "-", "");
        String extension = StringUtils.substring(uuid, 0, 16);
        String root = this.iheConfig.getAssigningAuthority();

        InstanceIdentifier id = new InstanceIdentifier();

        id.setRoot(root);
        id.setExtension(extension);

        try {

            this.patientIdentityService.addPatientIdentity(id);

            resp.getWriter().format("%s^^^&%s&ISO", extension, root);

        } catch (ServiceActionException e) {

            throw new ServletException(e);
        }
    }
}
